#pragma once

#include"Common.h"
#include"ThreadCache.h"
#include"PageCache.h"
#include"ObjectPool.h"

static void* ConcurrentAlloc(size_t size)     //初始化
{
	if (size > MAX_BYTES)       //大于256k，直接向pagecache申请
	{
		size_t alignSize = SizeClass::RoundUp(size);
		size_t kpage = alignSize >> PAGE_SHIFT;

		PageCache::GetInstance()->_pageMtx.lock();
		Span* span = PageCache::GetInstance()->NewSpan(kpage);
		span->objectSize = size;
		PageCache::GetInstance()->_pageMtx.unlock();

		void* ptr = (void*)(span->_pageid << PAGE_SHIFT);
		return ptr;
	}
	else
	{
		//使用TLS无锁的实现各线程使用自己的量
		if (pTLSThreadCache == nullptr)
		{
			//pTLSThreadCache = new ThreadCache();
			static ObjectPool<ThreadCache> tcPool;
			pTLSThreadCache = tcPool.New();
		}

		//cout << std::this_thread::get_id() << ":" << pTLSThreadCache << endl;   //调试日志

		return pTLSThreadCache->Allocate(size);
	}
}

//static void ConcurrentFree(void* pt,size_t size)    //释放
//{
//	if (size > MAX_BYTES)
//	{
//		Span* span = PageCache::GetInstance()->MapObjectToSpan(pt);
//
//		PageCache::GetInstance()->_pageMtx.lock();
//		PageCache::GetInstance()->ReleaseSpanToPageCache(span);
//		PageCache::GetInstance()->_pageMtx.unlock();
//	}
//	//assert(pTLSThreadCache);
//	pTLSThreadCache->Deallocate(pt,size);
//}

static void ConcurrentFree(void* pt)    //释放(不用传大小)
{
	Span* span = PageCache::GetInstance()->MapObjectToSpan(pt);
	if (span->objectSize > MAX_BYTES)
	{
		Span* span = PageCache::GetInstance()->MapObjectToSpan(pt);

		PageCache::GetInstance()->_pageMtx.lock();
		PageCache::GetInstance()->ReleaseSpanToPageCache(span);
		PageCache::GetInstance()->_pageMtx.unlock();
	}
	//assert(pTLSThreadCache);
	pTLSThreadCache->Deallocate(pt, span->objectSize);
}